/**
 * Created by showtan on 2019/1/27.
 * 登录(密码登录、快捷登录、新用户微信登录)
 */


import * as  Animatable from 'react-native-animatable';
class LoginScreen extends Component {
  static navigationOptions = ({ navigation }) => ({
    title: '账号登录'
  });
  constructor(props) {
    super(props);
    this.beforePhone = ''; // 获取验证码前手机号
    this.state = {
      isQuickLogin: false, // 是否快捷登录
      phone: '', // 手机号
      code: '', // 验证码
      password: '', // 密码
      loading: false,
    }
  }
  _getCode = (callback) => { // 获取验证码
    if (!Regular.phone(this.state.phone)) {
      Toast.fail('手机号不正确！');
    } else {
      Toast.success('验证码发送成功！');
    }
  }
  _login = (componentRef, animationType) => { // 密码/验证码登录
    componentRef.setNativeProps({ style: { zIndex: 1 } });
    componentRef.animate(animationType, 500).then(() => {
      componentRef.setNativeProps({ style: { zIndex: 0 } });
    });
    if (!Regular.phone(this.state.phone)) {
      Toast.fail('手机号不正确！');
    } else if (!this.state.isQuickLogin && !Regular.password(this.state.password)) {
      Toast.fail('密码不正确！');
    } else if (this.state.isQuickLogin && !Regular.checkcode(this.state.code)) {
      Toast.fail('验证码不正确！');
    } else {
      this.setState({ loading: true });
      this.timer = setTimeout(() => { this.setState({ loading: false }); this.props.navigation.goBack(); Toast.success('登录成功！'); }, 1500);
      // this.props.dispatch({ type: 'user/login', payload: { phone: this.state.phone, password: this.state.password } });
    }
  };
  componentWillUnmount() {
    this.timer && clearTimeout(this.timer);
  }
  render() {
    // 其他登录
    let otherLoginData = [{ image: Images.other.icon_weibo }, { image: Images.other.icon_weixin }, { image: Images.other.icon_qq }];
    let loginInformationData = [ // 手机号、验证码/密码
      { placeholder: '请输入手机号', secureTextEntry: false, keyboardType: 'numeric', changeFunc: (phone) => this.setState({ phone }), value: this.state.phone, clearFunc: () => this.setState({ phone: '' }) },
      { placeholder: '请输入验证码', secureTextEntry: false, keyboardType: 'numeric', changeFunc: (code) => this.setState({ code }), value: this.state.code, clearFunc: () => this.setState({ code: '' }) },
      { placeholder: '请输入6-16位的数字或字母', secureTextEntry: true, keyboardType: 'default', changeFunc: (password) => this.setState({ password }), value: this.state.password, clearFunc: () => this.setState({ password: '' }) }
    ];
    return <View style={styles.container}>
      <KeyboardAwareScrollView keyboardShouldPersistTaps='always' showsVerticalScrollIndicator={false}>
        <Image source={Images.other.icon_logo} style={styles.loginStyle} />
        {/* 登录需填信息 */}
        {loginInformationData.map((item, index) => {
          return (
            (this.state.isQuickLogin ? index != 2 : index != 1) && <View key={index}>
              <TextInput placeholder={item.placeholder} keyboardType={item.keyboardType}
                selectionColor={themeColor} secureTextEntry={item.secureTextEntry}
                underlineColorAndroid='transparent' maxLength={25}
                style={styles.textInputStyle}
                onChangeText={item.changeFunc} value={item.value} />
              {/* 清除text */}
              {index != 1 && item.value.length > 0 && <TouchableOpacity style={styles.clearTextCell} onPress={item.clearFunc}>
                <Image source={Images.other.icon_guanbi} style={{ width: adapt(15), height: adapt(15), tintColor: '#8f8e93' }} />
              </TouchableOpacity>}
              {/* 验证码 */}
              {index == 1 && <CheckButton onClick={this._getCode} ref='button' delay={60} btnStyle={styles.btnStyle} />}
            </View>
          )
        })}
        {/* 切换登录、忘记密码 */}
        <View style={[styles.forgetPsdCell, !this.state.isQuickLogin && { flexDirection: 'row', justifyContent: 'space-between' }]}>
          <Text onPress={() => this.setState({ isQuickLogin: !this.state.isQuickLogin, code: '', password: '' })} style={{ fontSize: adapt(10), color: '#4a4a4a', paddingVertical: adapt(5) }}>{this.state.isQuickLogin ? '切换密码登录' : '切换验证码登录'}</Text>
          {!this.state.isQuickLogin && <Animatable.Text animation='zoomIn' duration={500} style={{ fontSize: adapt(10), color: themeColor, paddingVertical: adapt(5) }}
            onPress={() => this.props.navigation.navigate('RegisterScreen', { isForget: true })}>忘记密码</Animatable.Text>}
        </View>
        {/* 登录、注册、其他登录 */}
        <AnimationCell animationType='pulse' text='登录' style={styles.regStyle}
          textStyle={{ marginTop: -adapt(1), color: '#fff' }} onPress={this._login} />
        <TouchableOpacity onPress={() => this.props.navigation.navigate('RegisterScreen', { isRegister: true })} activeOpacity={.6} style={styles.regCell}>
          <Text style={{ marginTop: -adapt(1), color: themeColor }}>注册</Text>
        </TouchableOpacity>
      </KeyboardAwareScrollView>
      {!this.state.isWechat && <View style={styles.bottomCell}>
        <View style={{ flexDirection: 'row', justifyContent: 'space-between', marginHorizontal: adapt(65) }}>
          {otherLoginData.map((item, index) => <TouchableOpacity activeOpacity={.6} onPress={() => { }} key={index}>
            <Image source={item.image} style={{ height: adapt(40), width: adapt(40) }} />
          </TouchableOpacity>)}
        </View>
        {/* 协议 */}
        <Text onPress={() => { }} style={{ fontSize: adapt(10), marginTop: adapt(20), alignSelf: 'center', backgroundColor: 'transparent', color: '#4a4a4a' }}>登录代表您已同意《版权声明》及《免责条款》</Text>
      </View>}
      {/* 缓冲modal */}
      <Modal transparent={true} visible={this.state.loading} onRequestClose={() => { }}>
        <View style={{ width: width, height: height, justifyContent: 'center', alignItems: 'center' }}>
          <Spinner isVisible={true} size={50} type='Circle' color={themeColor} />
        </View>
      </Modal>
    </View>
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#fff'
  },
  loginStyle: {
    width: adapt(120),
    height: adapt(120),
    marginLeft: (width - adapt(120)) / 2,
    marginVertical: isIphoneX() ? adapt(40) : adapt(30)
  },
  textInputStyle: {
    width: width - adapt(30),
    marginLeft: adapt(15),
    height: adapt(48),
    fontSize: adapt(12),
    paddingLeft: adapt(10),
    borderBottomWidth: adapt(2),
    borderColor: '#efefef'
  },
  clearTextCell: {
    position: 'absolute',
    top: adapt(15.5),
    right: adapt(25)
  },
  btnStyle: {
    position: 'absolute',
    top: adapt(13),
    right: adapt(25)
  },
  forgetPsdCell: {
    marginTop: adapt(10),
    marginHorizontal: adapt(25)
  },
  regStyle: {
    marginTop: adapt(20),
    width: adapt(120),
    height: adapt(50),
    marginLeft: (width - adapt(120)) / 2,
    backgroundColor: themeColor,
    borderRadius: adapt(5),
    alignItems: 'center',
    justifyContent: 'center',
    shadowOffset: { width: 2, height: 2, },
    shadowColor: '#D6D9DE',
    shadowOpacity: .3,
    elevation: 2,
    shadowRadius: 4
  },
  regCell: {
    marginTop: adapt(20),
    width: adapt(120),
    height: adapt(30),
    marginLeft: (width - adapt(120)) / 2,
    borderColor: themeColor,
    borderWidth: adapt(1),
    borderRadius: adapt(5),
    alignItems: 'center',
    justifyContent: 'center',
  },
  bottomCell: {
      width: width,
      position: 'absolute', 
      left: 0, 
      bottom: isIphoneX() ? 20 : 10
  },
});

LoginScreen.proptypes = {
  user: PropTypes.object,
  dispatch: PropTypes.func
}

function mapStateToProps({ user }) {
  return { user }
}

export default connect(mapStateToProps)(LoginScreen)